﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using dotnetCHARTING.WinForms;
using ViCode_LeVi.Data;
using ViCode_LeVi.Controls.Logs;
using ViCode_LeVi.Configs;
using System.Drawing.Drawing2D;

namespace ViCode_LeVi.Controls.Charts
{
    public partial class BarChartImportance : ChartCtrl
    {
        private FactorProperty[] m_aFactorProperties;
        private eImportanceMode m_evaluesbereich;

        public BarChartImportance()
        {
            this.InitializeComponent();
        }

        public override bool CreateChart()
        {
            LegendBox legendBox = null;
            bool flag = true;
            int riNumberOfElements = 0;
            try
            {
                base.SetChartBasis(eChartType.BarChartImportance, base.m_sXAxisLabel, base.m_sYAxisLabel);
                base.chart1.SeriesCollection.Clear();
                base.chart1.ExtraLegendBoxes.Clear();
                base.chart1.ExtraLegendEntries.Clear();
                base.chart1.XAxis.Markers.Clear();
                base.chart1.YAxis.Markers.Clear();
                if (VMConfig.Intance.Charts.LimitBarChartBarWidth)
                {
                    base.chart1.YAxis.StaticColumnWidth = ((float)(VMConfig.Intance.Charts.MaxBarChartBarWidth * base.ChartDPI)) / 96f;
                }
                else
                {
                    base.chart1.YAxis.StaticColumnWidth = 0f;
                }
                SeriesCollection seriesCollection = this.SetData(ref riNumberOfElements);
                base.NumberOfElements = riNumberOfElements;
                if (base.NumberOfElements > 0)
                {
                    base.chart1.SeriesCollection.Add(seriesCollection);
                    if (base.ChartLegendMode != eChartLegendMode.None)
                    {
                        legendBox = this.GetExtraLegendBox(this.m_aFactorProperties);
                        base.chart1.ExtraLegendBoxes.Add(legendBox);
                    }
                }
                else
                {
                    Series series = new Series("Empty")
                    {
                        LegendEntry = { Visible = true, Value = "" }
                    };
                    series.LegendEntry.LabelStyle.Color = Color.Empty;
                    Element element = new Element
                    {
                        Name = string.Empty,
                        YValue = 10.0,
                        Transparency = 100,
                        Color = Color.Empty
                    };
                    series.Elements.Add(element);
                    base.chart1.SeriesCollection.Add(series);
                }
                switch (this.m_evaluesbereich)
                {
                    case eImportanceMode.Absolute:
                        base.chart1.XAxis.DefaultTick.Label.Text = "%Value";
                        base.chart1.Title = ProjectData.Intance.Period.Tab6_Evaluation_Analysis_1_Absolute;
                        base.chart1.XAxis.Label.Text = ProjectData.Intance.Period.Tab6_Evaluation_Analysis_1_Absolute;
                        base.chart1.XAxis.Label.Font = new Font("Arial", 10f, FontStyle.Bold);
                        base.chart1.XAxis.Label.Color = Color.Black;
                        base.chart1.XAxis.Minimum = 0;
                        base.chart1.XAxis.Maximum = 10.5;
                        base.chart1.XAxis.Interval = 1.0;
                        foreach (Series series2 in base.chart1.SeriesCollection)
                        {
                            if (series2.Name != "Empty")
                            {
                                for (int i = 0; i < series2.Elements.Count; i++)
                                {
                                    if (series2.Elements[i].YValue == 0.0)
                                    {
                                        series2.Elements[i].YValue = 0.04;
                                    }
                                }
                            }
                        }
                        break;

                    case eImportanceMode.Relativ:
                        {
                            double xAxisBorderRelative = 0.0;
                            base.chart1.XAxis.DefaultTick.Label.Text = "%Value%";
                            base.chart1.Title = ProjectData.Intance.Period.Tab6_Evaluation_Analysis_1_Relativ;
                            base.chart1.XAxis.Label.Text = ProjectData.Intance.Period.Tab6_Evaluation_Analysis_1_Relativ;
                            base.chart1.XAxis.Label.Font = new Font("Arial", 10f, FontStyle.Bold);
                            base.chart1.XAxis.Label.Color = Color.Black;
                            xAxisBorderRelative = this.GetXAxisBorderRelative();
                            base.chart1.XAxis.Minimum = 0;
                            base.chart1.XAxis.Maximum = xAxisBorderRelative;
                            if (xAxisBorderRelative <= 16.0)
                            {
                                base.chart1.XAxis.Interval = 1.0;
                            }
                            else if (xAxisBorderRelative <= 51.0)
                            {
                                base.chart1.XAxis.Interval = 5.0;
                            }
                            else
                            {
                                base.chart1.XAxis.Interval = 10.0;
                            }
                            foreach (Series series3 in base.chart1.SeriesCollection)
                            {
                                if (series3.Name != "Empty")
                                {
                                    for (int j = 0; j < series3.Elements.Count; j++)
                                    {
                                        if (series3.Elements[j].YValue == 0.0)
                                        {
                                            series3.Elements[j].YValue = Convert.ToDouble(xAxisBorderRelative) / 250.0;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                }
                base.chart1.RefreshChart();
            }
            catch (Exception exception)
            {
                flag = false;
                //rsErr = "Fehler in BarChartImportance.CreateChart: " + exception.Message;
                Log.LogException(exception);
            }
            return flag;
        }
       
        private LegendBox GetExtraLegendBox(FactorProperty[] aFactorProperties)
        {
            bool flag = true;
            LegendBox box = new LegendBox();
            int count = 0;
            string id = string.Empty;
            try
            {
                box.Background = base.chart1.TitleBox.Background;
                box.CornerBottomRight = BoxCorner.Square;
                box.CornerBottomLeft = BoxCorner.Square;
                box.CornerTopLeft = BoxCorner.Square;
                box.CornerTopRight = BoxCorner.Square;
                box.LabelStyle = new dotnetCHARTING.WinForms.Label("", new Font("Arial", 8f), Color.Black);
                box.Line = new Line(Color.Black);
                box.Shadow.Soft = true;
                box.Shadow.Color = Color.Gray;
                box.Shadow.Depth = 5;
                box.ListTopToBottom = true;
                box.Orientation = base.ExtraLegendBoxOrientation;
                box.Template = "%Icon %CustomToken";
                if (aFactorProperties != null)
                {
                    count = aFactorProperties.Length;
                    foreach (FactorProperty property in aFactorProperties)
                    {
                        Color iconBackgroundColor = new Color();
                        FactorType type = property.Type;
                        if (type != FactorType.HK)
                        {
                            if (type == FactorType.SK)
                            {
                                goto Label_0111;
                            }
                            if (type == FactorType.BK)
                            {
                                goto Label_011A;
                            }
                        }
                        else
                        {
                            iconBackgroundColor = VMConfig.Intance.Colors.HK;
                        }
                        goto Label_0121;
                    Label_0111:
                        iconBackgroundColor = VMConfig.Intance.Colors.SK;
                        goto Label_0121;
                    Label_011A:
                        iconBackgroundColor = VMConfig.Intance.Colors.BK;
                    Label_0121:
                        switch (base.ChartLegendMode)
                        {
                            case eChartLegendMode.Full:
                                id = string.Format("{0}: {1}", property.Id, property.Name);
                                break;

                            case eChartLegendMode.Short:
                                id = property.Id;
                                break;
                        }
                        if (base.LegendWithPercent)
                        {
                            string str2 = string.Empty;
                            switch (this.m_evaluesbereich)
                            {
                                case eImportanceMode.Absolute:
                                    str2 = property.Importance.ToString("0");
                                    break;

                                case eImportanceMode.Relativ:
                                    str2 = property.ImportancePercent.ToString("0.00") + "%";
                                    break;
                            }
                            id = string.Format("{0} ({1})", id, str2);
                        }
                        LegendEntry legendEntry = new LegendEntry("", "", iconBackgroundColor)
                        {
                            SortOrder = count
                        };
                        legendEntry.CustomAttributes.Add("CustomToken", base.FormatLegendEntryText(id));
                        box.ExtraEntries.Add(legendEntry);
                        count--;
                    }
                }
                return box;
            }
            catch (Exception exception)
            {
                flag = false;
                Log.LogException(exception);
            }
            finally
            {
                if (!flag)
                {
                    box.ExtraEntries.Clear();
                }
            }
            return box;
        }
        public Func<Step_TaskItemGroup[]> Func_GetStep_TaskItemGroup;
        private FactorProperty[] GetFactorProperties()
        {
            bool flag = true;
            List<FactorProperty> list = new List<FactorProperty>();
            Step_TaskItemGroup[] grps = Func_GetStep_TaskItemGroup == null ? null : Func_GetStep_TaskItemGroup();
            if (grps == null)
                return new FactorProperty[0];
            foreach (var group in grps)
            {
                var data = group.Tasks_Source.Select(c => new FactorProperty()
                {
                    Quality = c.Quanlity_WeightPercent.HasValue == false ? 0 : (double)c.Quanlity_WeightPercent.Value
                     ,
                    Quantity = c.Quantity_WeightPercent.HasValue == false ? 0 : (double)c.Quantity_WeightPercent.Value
                     ,
                    Systematic = c.Systematic_WeightPercent.HasValue == false ? 0 : (double)c.Systematic_WeightPercent.Value
                     ,
                    Importance = c.Weight
                     ,
                    Name = c.Name
                     ,
                    XPercent = 0
                     ,
                    YPercent = 0
                     ,
                    Id = c.ID,
                    BubblePercent = 0,
                    BubbleSize = (c.Systematic_WeightPercent.HasValue == false ? 0 : (double)c.Systematic_WeightPercent.Value) + 25,
                    Marker = string.Empty
                     ,
                    XPotential = c.Quanlity_WeightPercent.HasValue == false ? 0 : (double)c.Quanlity_WeightPercent.Value
                     ,
                    YPotential = c.Weight
                     ,
                    Type = group.FactorType
                     ,
                    ImportancePercent = c.Weight
                     ,
                    EvaluatedDimensions = 50
                }).ToArray();
                list.AddRange(data);
            }
            //Todo
            //FactorProperty property = new FactorProperty();
            //try
            //{
            //    RootData oProject = RootData.Intance;
            //    if (oProject != null)
            //    {
            //        Hashtable hashtable = DH.CalcRelativeImportance(oProject, oProject.CurrentPeriod, true);
            //        FactorList list2 = oProject.ValidFactorsForCurrentPeriod(true);
            //        if (list2 == null)
            //        {
            //            return list;
            //        }
            //        foreach (Factor factor in list2)
            //        {
            //            if (((factor != null) && (factor.Type != FactorType.GE)) && ((factor.Type != FactorType.GP) && (factor.Type != FactorType.UNKNOWN)))
            //            {
            //                FactorExtension extension = factor.ExtensionForPeriod(oProject.CurrentPeriod);
            //                property = new FactorProperty
            //                {
            //                    Id = factor.LogicalID,
            //                    Name = factor.Name,
            //                    Type = factor.Type,
            //                    Importance = extension.Importance,
            //                    ImportancePercent = Math.Round(Convert.ToDouble(hashtable[factor.ID]), 2)
            //                };
            //                list.Add(property);
            //            }
            //        }
            //    }
            //    return list;
            //}
            //catch (Exception exception)
            //{
            //    flag = false;
            //    Log.LogException(exception);
            //}
            //finally
            //{
            //    if (!flag)
            //    {
            //        list.Clear();
            //    }
            //}
            return list.ToArray();
        }

        private double GetXAxisBorderRelative()
        {
            double num = 0.0;
            double num2 = 0.0;
            foreach (Series series in base.chart1.SeriesCollection)
            {
                if (!(series.Name != "Empty"))
                {
                    goto Label_010A;
                }
                for (int i = 0; i < series.Elements.Count; i++)
                {
                    num = Math.Max(num, series.Elements[i].YValue);
                }
                num2 = Math.Ceiling(num);
                if (num2 <= 16.0)
                {
                    num2 += 0.5;
                }
                else
                {
                    if (num2 > 51.0)
                    {
                        goto Label_00E6;
                    }
                    while ((num2 % 5.0) != 0.0)
                    {
                        num2++;
                    }
                    num2 += 2.5;
                }
                continue;
            Label_00DA:
                num2++;
            Label_00E6:
                if ((num2 % 10.0) != 0.0)
                {
                    goto Label_00DA;
                }
                num2 += 5.0;
                continue;
            Label_010A:
                num2 = 105.0;
            }
            return num2;
        }
   
        public void ReadOptions()
        {
            base.ReadGeneralDisplayOptions(eChartType.BarChartImportance);
            this.ReadOwnDisplayOptions();
        }

        private void ReadOwnDisplayOptions()
        {
            try
            {
                //todo
                this.valuesbereich = eImportanceMode.Absolute;// base.MapImportanceModeString(oProject.Params.ChartDisplayOptions[eChartType.BarChartImportance.ToString() + ".valuesbereich"]);
            }
            catch (Exception exception)
            {
                Log.LogException(exception);
            }
        }

        protected override SeriesCollection SetData(ref int riNumberOfElements)
        {
            RootData oProject = RootData.Intance; 
            SeriesCollection seriess = new SeriesCollection();
            bool flag = false;
            bool flag2 = false;
            bool flag3 = false;
            try
            {
                this.m_aFactorProperties = this.GetFactorProperties();
                this.m_aFactorProperties.Reverse();
                Series series = new Series
                {
                    PaletteName = Palette.One
                };
                foreach (FactorProperty property in this.m_aFactorProperties)
                {
                    Element element = new Element();
                    switch (this.m_evaluesbereich)
                    {
                        case eImportanceMode.Absolute:
                            element.YValue = property.Importance;
                            element.ToolTip = string.Format("{0}: {1} (Weighting relativ: {2}%)", property.Name, property.Importance, property.ImportancePercent.ToString("0.00"));
                            break;

                        case eImportanceMode.Relativ:
                            element.YValue = property.ImportancePercent;
                            element.ToolTip = string.Format("{0}: {1}% (Weighting: {2})", property.Name, property.ImportancePercent.ToString("0.00"), property.Importance);
                            break;
                    }
                    element.LegendEntry.LabelStyle.Font = new Font("Arial", 9f, FontStyle.Regular);
                    element.LegendEntry.LabelStyle.Color = Color.Black;
                    FactorType type = property.Type;
                    if (type != FactorType.HK)
                    {
                        if (type == FactorType.SK)
                        {
                            goto Label_01C7;
                        }
                        if (type == FactorType.BK)
                        {
                            goto Label_0223;
                        }
                    }
                    else
                    {
                        element.Color = VMConfig.Intance.Colors.HK;
                        if (VMConfig.Intance.Charts.BarChartHatching)
                        {
                            element.HatchStyle = HatchStyle.BackwardDiagonal;
                        }
                        if (!flag)
                        {
                            element.LegendEntry.Visible = true;
                            element.LegendEntry.Name = "Human Capital";//"Human Capital"
                            element.LegendEntry.SortOrder = 1;
                            flag = true;
                        }
                        else
                        {
                            element.LegendEntry.Visible = false;
                        }
                    }
                    goto Label_027D;
                Label_01C7:
                    element.Color = VMConfig.Intance.Colors.SK;
                    if (VMConfig.Intance.Charts.BarChartHatching)
                    {
                        element.HatchStyle = HatchStyle.Cross;
                    }
                    if (!flag3)
                    {
                        element.LegendEntry.Visible = true;
                        element.LegendEntry.Name = RootData.Intance.Report_SucessFactor_Structural;// "Structural Capital";//"Structural Capital"
                        element.LegendEntry.SortOrder = 2;
                        flag3 = true;
                    }
                    else
                    {
                        element.LegendEntry.Visible = false;
                    }
                    goto Label_027D;
                Label_0223:
                    element.Color = VMConfig.Intance.Colors.BK;
                    if (VMConfig.Intance.Charts.BarChartHatching)
                    {
                        element.HatchStyle = HatchStyle.ForwardDiagonal;
                    }
                    if (!flag2)
                    {
                        element.LegendEntry.Visible = true;
                        element.LegendEntry.Name = RootData.Intance.Report_SucessFactor_Relational;// "Relational Capital";//"Relational Capital"
                        element.LegendEntry.SortOrder = 3;
                        flag2 = true;
                    }
                    else
                    {
                        element.LegendEntry.Visible = false;
                    }
                Label_027D:
                    switch (base.ChartLabelMode)
                    {
                        case eChartLabelMode.Full:
                            element.Name = string.Format("{0}: {1}", property.Id, property.Name);
                            goto Label_03D5;

                        case eChartLabelMode.FullWithValue:
                            element.ShowValue = true;
                            if (this.valuesbereich != eImportanceMode.Relativ)
                            {
                                break;
                            }
                            element.SmartLabel.Text = property.ImportancePercent.ToString("0.00") + "%";
                            goto Label_0324;

                        case eChartLabelMode.Short:
                            element.Name = property.Id;
                            goto Label_03D5;

                        case eChartLabelMode.ShortWithValue:
                            element.ShowValue = true;
                            if (this.valuesbereich != eImportanceMode.Relativ)
                            {
                                goto Label_0396;
                            }
                            element.SmartLabel.Text = property.ImportancePercent.ToString("0.00") + "%";
                            goto Label_03B7;

                        default:
                            element.Name = property.Id;
                            goto Label_03D5;
                    }
                    element.SmartLabel.Text = property.Importance.ToString("0");
                Label_0324:
                    element.Name = string.Format("{0}: {1}", property.Id, property.Name);
                    goto Label_03D5;
                Label_0396:
                    element.SmartLabel.Text = property.Importance.ToString("0");
                Label_03B7:
                    element.Name = property.Id;
                Label_03D5:
                    series.Elements.Add(element);
                }
                riNumberOfElements = series.Elements.Count;
                seriess.Add(series);
            }
            catch (Exception exception)
            {
                seriess.Clear();
                Log.LogException(exception);
            }
            return seriess;
        }

        public void WriteOptions(ProjectData oProject)
        {
            base.WriteGeneralDisplayOptions(eChartType.BarChartImportance);
            this.WriteOwnDisplayOptions();
        }

        private void WriteOwnDisplayOptions()
        {
            try
            {
                //todo
                //oProject.Params.ChartDisplayOptions[eChartType.BarChartImportance.ToString() + ".valuesbereich"] = base.MapImportanceMode(this.valuesbereich);
            }
            catch (Exception exception)
            {
                Log.LogException(exception);
            }
        }

        public eImportanceMode valuesbereich
        {
            get
            {
                return this.m_evaluesbereich;
            }
            set
            {
                this.m_evaluesbereich = value;
            }
        }
    }
}
